package com.apex.sdk.ui;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.apex.bluetooth.callback.OtaCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apex.bluetooth.model.EABleOta;
import com.apex.bluetooth.utils.LogUtils;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivityHlPointBinding;
import com.apex.sdk.dialog.WaitingDialog;
import com.apex.sdk.model.WatchInfo;
import com.apex.sdk.utils.HLDialUtils;
import com.example.custom_dial.CustomDialCallback;
import com.example.custom_dial.HLPointUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;


public class HLPointDialActivity extends AppCompatActivity {
    final String TAG = this.getClass().getSimpleName();
    private WatchInfo watchInfo;
    private Bitmap backBitmap;
    private Bitmap preBitmap;
    private Bitmap hBitmap, mBitmap, sBitmap;
    private WaitingDialog waitingDialog;
    private boolean isInstalling;
    private String filePath;
    HLPointUtils hlPointUtils;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                if (msg.what == 0x41) {
                    if (waitingDialog != null && waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                } else if (msg.what == 0x42) {
                    if (waitingDialog != null && waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                    Log.e(TAG, "将缩略图展示在界面上");
                    Bitmap pBitmap = (Bitmap) msg.obj;
                    activityHlPointBinding.previewImage.setImageBitmap(pBitmap);
                } else if (msg.what == 0x43) {
                    if (backBitmap == null) {
                        Log.e(TAG, "背景图不存在");
                        isInstalling = false;
                        if (waitingDialog != null) {
                            waitingDialog.dismiss();
                        }
                        Toast.makeText(HLPointDialActivity.this, getString(R.string.Create_dial_fail), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    new HLDialUtils().createPointDialBin(hlPointUtils, backBitmap, preBitmap, hBitmap, mBitmap, sBitmap, new CustomDialCallback() {
                        @Override
                        public void dialPath(String dPath) {
                            if (TextUtils.isEmpty(dPath)) {
                                isInstalling = false;
                                if (waitingDialog != null) {
                                    waitingDialog.dismiss();
                                }
                                Toast.makeText(HLPointDialActivity.this, getString(R.string.Create_dial_fail), Toast.LENGTH_SHORT).show();
                            } else {
                                filePath = dPath;
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(0x52);
                                }
                            }
                        }
                    }, watchInfo.lcd_full_w,watchInfo.lcd_full_h);

                } else if (msg.what == 0x52) {
                    if (EABleManager.getInstance().getDeviceConnectState() == EABleConnectState.STATE_CONNECTED) {
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                byte[] fileByte = file2Byte();
                                if (fileByte != null) {
                                    Log.e(TAG, "最终文件大小:" + fileByte.length);
                                    List<EABleOta> otaList = new ArrayList<>();
                                    EABleOta eaBleOta = new EABleOta();
                                    eaBleOta.setOtaType(EABleOta.OtaType.user_wf);
                                    eaBleOta.setPop(true);
                                    eaBleOta.setFileBytes(fileByte);
                                    otaList.add(eaBleOta);
                                    EABleManager.getInstance().otaUpdate(otaList, new OtaCallback() {
                                        @Override
                                        public void success() {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x53);
                                            }
                                        }

                                        @Override
                                        public void progress(int progress) {
                                            LogUtils.e(TAG, "当前进度:" + progress + "%");
                                        }

                                        @Override
                                        public void mutualFail(int errorCode) {
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x54);
                                            }
                                        }
                                    });
                                    //   } else {
                                    //       Log.e(TAG, "文件转换的字节数组不存在");
                                }


                            }
                        }.start();
                    } else {
                        isInstalling = false;
                        if (waitingDialog != null && waitingDialog.isShowing()) {
                            waitingDialog.dismiss();
                        }
                        Toast.makeText(HLPointDialActivity.this, getString(R.string.disconnect), Toast.LENGTH_SHORT).show();
                    }
                } else if (msg.what == 0x53) {
                    isInstalling = false;
                    if (waitingDialog != null && waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                    Toast.makeText(HLPointDialActivity.this, getString(R.string.ota_success), Toast.LENGTH_SHORT).show();
                } else if (msg.what == 0x54) {
                    isInstalling = false;
                    if (waitingDialog != null && waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                    Toast.makeText(HLPointDialActivity.this, getString(R.string.ota_failed), Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    private byte[] file2Byte() {
        byte[] fileByte = null;
        if (!TextUtils.isEmpty(filePath)) {
            Log.e(TAG, "文件地址存在");
            try {
                FileInputStream fis = new FileInputStream(filePath);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int n;
                while ((n = fis.read(b)) != -1) {
                    bos.write(b, 0, n);
                }
                fis.close();
                bos.close();
                fileByte = bos.toByteArray();
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        } else {
            Log.e(TAG, "文件地址不存在");
        }

        return fileByte;
    }

    ActivityHlPointBinding activityHlPointBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityHlPointBinding = ActivityHlPointBinding.inflate(getLayoutInflater());
        setContentView(activityHlPointBinding.getRoot());
        activityHlPointBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityHlPointBinding.tool);
        getSupportActionBar().setTitle(null);
        watchInfo = (WatchInfo) getIntent().getSerializableExtra("param");
        hlPointUtils = new HLPointUtils(HLPointDialActivity.this, watchInfo.lcd_pix_type);
        activityHlPointBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Log.e(TAG, "将背景图转换成合适尺寸");
        //  new BitmapScale(R.drawable.black_point_360_400_dial).start();
        activityHlPointBinding.colorRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                getCurrentColor(checkedId);
            }
        });
        activityHlPointBinding.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (backBitmap == null || preBitmap == null) {
                    return;
                }
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(HLPointDialActivity.this);
                }
                if (!waitingDialog.isShowing()) {
                    waitingDialog.show();
                }
                isInstalling = true;
                new PointScale().start();

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "生成缩略图");
        getCurrentColor(activityHlPointBinding.colorRadio.getCheckedRadioButtonId());
    }

    private void getCurrentColor(int rid) {
        if (rid == R.id.red) {//更新前置预览图
            if (waitingDialog == null) {
                waitingDialog = new WaitingDialog(HLPointDialActivity.this);
            }
            if (!waitingDialog.isShowing()) {
                waitingDialog.show();
            }
            new BitmapScale(R.drawable.thum_white_point_240).start();

        } else if (rid == R.id.green) {
            if (waitingDialog == null) {
                waitingDialog = new WaitingDialog(HLPointDialActivity.this);
            }
            if (!waitingDialog.isShowing()) {
                waitingDialog.show();
            }
            new BitmapScale(R.drawable.thum_black_point_240).start();
        }
    }

    class BitmapScale extends Thread {
        int res;

        public BitmapScale(int res) {
            this.res = res;
        }

        @Override
        public void run() {
            super.run();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inScaled = false;
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lie_sheng_back_466x466_bg, options);
            preBitmap = BitmapFactory.decodeResource(getResources(), res, options);
            //将缩略图调整尺寸

            if (watchInfo.lcd_full_w == 240) {
                if (watchInfo.lcd_full_type == 1) {
                    backBitmap = Bitmap.createBitmap(240, 240, Bitmap.Config.ARGB_8888);
                } else {
                    backBitmap = Bitmap.createBitmap(240, 280, Bitmap.Config.ARGB_8888);
                }
            } else {
                backBitmap = Bitmap.createBitmap(360, 360, Bitmap.Config.ARGB_8888);
            }
            Canvas canvas = new Canvas(backBitmap);
            if (watchInfo.lcd_full_w == 240) {
                if (watchInfo.lcd_full_type == 1) {
                    canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(0, 0, 240, 240), new Paint());
                } else {
                    canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(0, 0, 240, 280), new Paint());
                }
            } else {
                canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(0, 0, 360, 360), new Paint());
            }
            Log.e(TAG, "获取到的图片宽:" + bitmap.getWidth() + ",获取到的图片高:" + bitmap.getHeight());
            //组合

            bitmap.recycle();
            if (preBitmap != null) {
                //生成缩略图
                HLDialUtils hlDialUtils = new HLDialUtils();
                Bitmap pBitmap = hlDialUtils.createPointPreviewDial(hlPointUtils, backBitmap, preBitmap,watchInfo.lcd_full_w,watchInfo.lcd_full_h);
                if (mHandler != null) {
                    Message message = new Message();
                    message.what = 0x42;
                    message.obj = pBitmap;
                    mHandler.sendMessage(message);
                }
            } else {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(0x41);
                }
            }

        }
    }

    class PointScale extends Thread {
        @Override
        public void run() {
            super.run();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inScaled = false;
            if (watchInfo.lcd_full_w == 240) {
                hBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.point_hour_black_240, options);
                mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.point_minute_black_240, options);
                sBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.point_second_black_240, options);
            } else {
                hBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lie_sheng_point_hour_360, options);
                mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lie_sheng_point_minute_360, options);
                sBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lie_sheng_point_second_360, options);
            }

            if (mHandler != null) {
                mHandler.sendEmptyMessage(0x43);
            }

        }
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (hlPointUtils != null) {
            hlPointUtils.destroy();
            hlPointUtils = null;
        }
        backBitmap = null;
        watchInfo = null;
        preBitmap = null;
        hBitmap = null;
        mBitmap = null;
        sBitmap = null;
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        super.onDestroy();
    }

}
